import $router from '@/router';
import { message as $message } from 'ant-design-vue';
import { parseCode, showModal, showMsg } from './helper';
import { IStrategieInParams, IStrategieType } from './index.type';
/**
 * @desc 策略
 */
const strategies: Record<
  IStrategieType,
  (obj: IStrategieInParams) => string | undefined
> = {
  // 业务逻辑异常
  BUSINESS_ERROR({ data, config, codeKey, codeValue, msgKey }) {
    const message = data[msgKey] || '系统异常，请稍后再试';
    data[codeKey] = parseCode(data[codeKey]);
    if (data[codeKey] === codeValue) {
      config.codeErrTip && showMsg(message);
      return message;
    }
  },
  // 没有授权登录
  NOT_AUTH({ data, codeKey, codeValue, config }) {
    const message = '用户登录超时，请重新登录';
    data[codeKey] = parseCode(data[codeKey]);
    if (data[codeKey] === codeValue) {
      $message.destroy();
      showMsg(message);
      const currentRoute = $router.currentRoute;
      if (currentRoute.value.name === 'Login') {
        return message;
      }
      config.redirectToLogin &&
        $router.replace({
          path: '/login',
          query: {
            redirect: currentRoute.value.fullPath
          }
        });
      return message;
    }
  },
  // 权限不足
  PERMISSION_DENIED({ data, codeKey, codeValue }) {
    const message = '权限不足，请您联系管理员';
    data[codeKey] = parseCode(data[codeKey]);
    if (data[codeKey] === codeValue) {
      showModal(message);
      return message;
    }
  },
  // 系统异常
  SYSTEM_ERROR({ data, codeKey, codeValue }) {
    const message = '系统异常，请稍后再试';
    data[codeKey] = parseCode(data[codeKey]);
    if (data[codeKey] === codeValue) {
      showModal(message);
      return message;
    }
  }
};

export default strategies;
